package com.fkdx.webman.controller;

import com.alibaba.fastjson.JSON;
import com.fkdx.common.utils.DateUtil;
import com.fkdx.dao.entity.PageResult;
import com.fkdx.service.TaskService;
import com.fkdx.service.dto.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;
import com.fkdx.common.dto.ResponseDTO;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import com.alibaba.excel.EasyExcel;

/**
 * 任务controller
 */
@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {

    @Resource
    private TaskService taskService;

    @GetMapping("/list")
    public PageResult<TaskQueryResp> getTaskList(TaskQueryReq req) {
        return taskService.getTaskList(req);
    }

    @GetMapping("/form")
    public TaskQueryResp getTaskForm(Long id) {
        return taskService.getTaskForm(id);
    }

    @PostMapping("/save")
    public ResponseDTO<String> saveTaskForm(@RequestBody @Valid TaskReq req) {
        taskService.saveTaskForm(req);
        return ResponseDTO.buildSuccessDataResp("ok");
    }
    @PostMapping("/add")
    public ResponseDTO<String> addTaskForm(@RequestBody @Valid TaskReq req) {
        log.info("回调任务完成{}", JSON.toJSONString(req));
        taskService.addTaskForm(req);
        return ResponseDTO.buildSuccessDataResp("ok");
    }

    @PostMapping("/remove")
    public ResponseDTO<String> removeTaskList(@RequestBody Long[] id) {
        taskService.removeTaskList(id);
        return ResponseDTO.buildSuccessDataResp("ok");
    }
    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）https://github.com/alibaba/easyexcel
     * <p>
     * 1. 创建excel对应的实体对象 参照{}
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/downloadList")
    @ApiOperation(value = "下载附件")
    public void downloadList(HttpServletResponse response,@Param("ids") String ids) {
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(DateUtil.getYYYY_MM_DD(), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TaskDownResp.class).sheet("统计表").doWrite(taskService.downloadList(ids));
        } catch (Exception e) {
            log.error("下载失败：", e);
            throw new RuntimeException("下载失败", e);
        }
    }
}
